package com.ogilvy.audi.webapp.action.page;


import com.ogilvy.audi.model.util.PageParameter;
import com.ogilvy.audi.service.GenericManager;
import com.ogilvy.audi.webapp.util.PageConstants;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.json.annotations.JSON;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: User
 * Date: 2009-1-12
 * Time: 0:51:54
 * To change this template use File | Settings | File Templates.
 */
public abstract class DWZPageAction extends PageAction {
    	protected static int PAGE_SIZE = PageConstants.DEFAULT_DISPLAYTAG_SIZE;


        protected String pageNum;
        protected String numPerPage;
        protected String orderField;
        protected String currentPage;
        protected String orderDirection="desc";

       protected String navTabId;
       protected String callbackType;
       protected String forwardUrl;
       protected String statusCode;
        protected String selfMsg;
        protected String msgTip;
        protected String target;
        protected String saveButton="true";


    protected DWZPageAction() {
        log.debug("Entering pageAction constract") ;
          if(null==forwardUrl){
                forwardUrl=getRequest().getParameter("forwardUrl");
//                log.debug("The forwardUrl is "+getRequest().getParameter("forwardUrl")) ;

          }
         if(StringUtils.isNotBlank(forwardUrl)){
               log.debug("The forwardUrl is "+forwardUrl) ;
              String org_url=BASE64Decoder(forwardUrl);
             this.getRequest().setAttribute("f_url",org_url);
             log.debug("The org url is "+org_url) ;
         }
//        if(StringUtils.isNotBlank(getFormMethod())){
//                  this.getRequest().setAttribute("formMethod",getFormMethod());
//        }


    }

    @JSON(serialize=false)
	protected String getSortColumn() {
	return orderField;
	}
     @JSON(serialize=false)
	protected String getSortOrder() {
		return  orderDirection;
	}


  @JSON(serialize=false)
	protected int getPageNumber() {

    //String   pageNumberString=  aRequest.getParameter("pageNum");
      // log.debug("The pagerNum is "+pageNumberString) ;
		int pageNumber = 1;
		if (!StringUtils.isBlank(pageNum)) {
			try {
				pageNumber = (Integer.parseInt(pageNum));
			} catch (NumberFormatException e) {
				// Do nothing... assume startRecord is 0;
			}
		}
		return pageNumber;
	}


  @Override
	public List searchCondition(String equals,String... paras){
        log.debug("Entering searchCondition method") ;
             initURLMap();
          if(null==equals)
            equals="";
         HttpServletRequest request=this.getRequest();
		String TABLE_ID = getTableId();
		int page_size = getPageSize();
		GenericManager mgr = getManager();

		String sortColumn = getSortColumn();
		String sortOrder = getSortOrder();
		int pageNumber = getPageNumber();
		int firstRecord = (pageNumber - 1) * page_size;
		String resultSql = "first";
		if (request.getAttribute(getTableId()) == null) {
           Map condition=getSearchCondition();
             if(StringUtils.isNotBlank(sortColumn)){
               List sortList=(List)condition.get(PageConstants.DEFAULT_SORT_NAME);
                 PageParameter sortPar=new PageParameter();
                  sortPar.setParName(sortColumn);
                  sortPar.setParValue(sortOrder);
                sortList.add(sortPar);
             }

            List list= mgr.getRecordsByCondition(
					firstRecord, page_size,  condition,equals, paras);


			request.setAttribute(getTableId(),list);

			resultSql = (String) condition.get("resultsql");


			Collection dateSet = (Collection) condition.get("dateSet");
 log.debug("The result size sql is "+resultSql) ;
			request.setAttribute("resultSize", mgr
					.getRecordSizeBySql(resultSql,dateSet));

            request.setAttribute("pageSize",page_size);
            request.setAttribute("currentPage",pageNumber);
			if (log.isDebugEnabled()) {
				log.debug("return sql is " + resultSql);
				log.debug("return list is " + list.size());
			}
            return list;
		}
        return new ArrayList();
	}






     @JSON(serialize=false)
	public  int getPageSize(){
        // String pageSize= this.getRequest().getParameter("pageSize");
      //   log.debug("The pageSize is "+pageSize) ;
            if(StringUtils.isBlank(numPerPage))
		return PAGE_SIZE;
          else
         return     Integer.valueOf(numPerPage);
	}





    public  Map getSearchCondition(){
        log.debug("Entering super getSearchCondition method");
      Map condition = PageConstants.initConditionMap();
      List parList=(List)condition.get(PageConstants.DEFAULT_PARA_NAME);
      List dateList=(List)condition.get(PageConstants.DEFAULT_DATE_NAME);
      List sortList=(List)condition.get(PageConstants.DEFAULT_SORT_NAME);
        if(StringUtils.isNotBlank(name)){
           PageParameter par=new PageParameter();
            par.setParName("geneAttribute.name");
            par.setParValue(name);
            par.setFuzzyStatus(true);
            parList.add(par);
        }

         if(StringUtils.isNotBlank(description)){
            PageParameter par=new PageParameter();
            par.setParName("geneAttribute.description");
            par.setParValue(description);
            par.setFuzzyStatus(true);
            parList.add(par);
        }
        if(StringUtils.isNotBlank(startDate)){
            PageParameter date=new PageParameter();
            date.setParName("sDate_geneAttribute.createTime");
            date.setParValue(startDate);
            dateList.add(date);
        }

        if(StringUtils.isNotBlank(endDate)){
            PageParameter date=new PageParameter();
            date.setParName("eDate_geneAttribute.createTime");
            date.setParValue(endDate);
            dateList.add(date);
        }



       return PageConstants.condition;
    }


    public String getPageNum() {
        return pageNum;
    }

    public void setPageNum(String pageNum) {
        this.pageNum = pageNum;
    }

    public String getNumPerPage() {
        return numPerPage;
    }

    public void setNumPerPage(String numPerPage) {
        this.numPerPage = numPerPage;
    }

    public String getOrderField() {
        return orderField;
    }

    public void setOrderField(String orderField) {
        this.orderField = orderField;
    }

    public String getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(String currentPage) {
        this.currentPage = currentPage;
    }

    public String getOrderDirection() {
        return orderDirection;
    }

    public void setOrderDirection(String orderDirection) {
        this.orderDirection = orderDirection;
    }

    public String getNavTabId() {
//         if(this.getCallbackType().equals("closeCurrent"))
//             return "";
        return navTabId;
    }

    public void setNavTabId(String navTabId) {
        this.navTabId = navTabId;
    }

    public String getForwardUrl() {
        return forwardUrl;
    }

    public void setForwardUrl(String forwardUrl) {
        this.forwardUrl = forwardUrl;
    }

    public String getStatusCode() {
           if(StringUtils.isBlank(statusCode))
                statusCode="200";
        return statusCode;
    }

    public void setStatusCode(String statusCode) {
        this.statusCode = statusCode;
    }

    public String getSelfMsg() {
        //String msg=this.getSelfMsg();

         // selfMsg+=":'"+msg+"'";
        return selfMsg;
    }

    public void setSelfMsg(String selfMsg) {
        this.selfMsg = selfMsg;
    }

    public String getCallbackType() {
               if(null==callbackType||StringUtils.isBlank(forwardUrl)||StringUtils.isBlank(navTabId))
                   callbackType="closeCurrent";
        return callbackType;
    }

    public void setCallbackType(String callbackType) {
        this.callbackType = callbackType;
    }

    public String getMsgTip() {
         if(StringUtils.isBlank(this.getSelfMsg())){
               msgTip=  getSystemMsg();
         }else{
                msgTip=this.getSystemMsg() +"("+this.getSelfMsg()+")";
         }
        return msgTip;
    }



    private String getSystemMsg(){
         if(this.statusCode.equals("200")){
            return this.getText("200.message");
         }
        if(this.statusCode.equals("300")){
           return this.getText("300.message");
         }
        if(this.statusCode.equals("301")){
            return this.getText("301.message");
         }
        return getText("200.message");
    }

	private static String BASE64Decoder(String src){
		if(null==src || "".equals(src.trim())||"null".equalsIgnoreCase(src)){
			return "";
		}
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] raw = null;
		try {
			raw = decoder.decodeBuffer(src);
		} catch (IOException e) {

			e.printStackTrace();
		}
		return new String(raw);
	}

    public String getTarget() {
         if(null==target)
             target="dialog";
        return target;
    }

    public void setTarget(String target) {
        this.target = target;
    }

    public String getSaveButton() {
        return saveButton;
    }

    public void setSaveButton(String saveButton) {
        this.saveButton = saveButton;
    }

    public  abstract GenericManager getManager();

	public abstract String getTableId();

    /**
     * FORM 提交 方法名称
     * @return
     */
    public abstract String getFormMethod();



    /**
     * 搜索 URL
     * @return
     */
    public  abstract String getSearchUrl();

    /**
     * 编辑URL
     * @return
     */
    public abstract String getEditUrl() ;
        /**
     * 新增URL
     * @return
     */
    public abstract String getAddUrl();
        /**
     * 删除URL
     * @return
     */
    public  abstract String getDelUrl();
        /**
     * 高级检索 URL
     * @return
     */
    public  abstract String getAdvSearchUrl();


    /**
     * 将自定义 参数    存入MAP 中
     * @param parMap
     */
    public void putExpansionParameter(Map parMap){

    }

    protected void initURLMap(){
        log.debug("Entering initUrl Map") ;
        Map parMap =(Map)getRequest().getAttribute("parMap") ;
                if(null!=parMap){
                     return;
                }
             parMap=new HashMap();
                    getRequest().setAttribute("parMap",parMap) ;
         parMap.put(PageConstants.SEARCH_URL_NAME, decorateUrl(getSearchUrl()));
         parMap.put(PageConstants.EDIT_URL_NAME, decorateUrl(getEditUrl()));
         parMap.put(PageConstants.ADD_URL_NAME, decorateUrl(getAddUrl()));
         parMap.put(PageConstants.DEL_URL_NAME, decorateUrl(getDelUrl()));
         parMap.put(PageConstants.TABLE_ID_NAME, getTableId());
         parMap.put(PageConstants.ADV_SEARCH_URL_NAME, getAdvSearchUrl());
         //parMap.put(PageConstants.SAVE_FORM_METHOD_NAME, getFormMethod());
         putExpansionParameter(parMap);

    }

    /**
     * 装饰 URL
     * @param url
     * @return
     */
    protected String decorateUrl(String url){
         if(StringUtils.isBlank(url))
             return "";
        if(url.indexOf("?")>0)
            url+="&";
        else
            url+="?";
       String cur_url=(String) this.getRequest().getAttribute("cur_url");

        String  call_back_type="forward";
         if(StringUtils.isBlank(cur_url)){
                   call_back_type="closeCurrent";
         }
        url+="navTabId="+this.getNavTabId()+"&callbackType="+call_back_type+"&forwardUrl="+cur_url;
        log.debug("The url is "+url) ;
        return url;
    }


}